import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:school_assistant/data/usr_extra_entity.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:school_assistant/user_feedback_imgs.dart';
import 'package:sp_util/sp_util.dart';

import 'common_client.dart';
import 'common_colors.dart';
import 'data/base_data_entity.dart';
import 'data/uer_info_entity.dart';

class PriInfoPage extends StatefulWidget {
  const PriInfoPage({Key? key}) : super(key: key);

  @override
  State<PriInfoPage> createState() => _PriInfoPageState();
}

class _PriInfoPageState extends State<PriInfoPage> {
  final _controllerDes = TextEditingController();
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _controllerDes.dispose();
    _nameController.dispose();
    _phoneController.dispose();
  }

  XFile? imgFeed;

  UerInfoEntity? uerInfo;

  int curSex = 1;

  getLostData() async {
    final ImagePicker picker = ImagePicker();
    imgFeed =
        await picker.pickImage(source: ImageSource.gallery, imageQuality: 70);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: CommonColor.colorF5,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        title: Text(
          "我的信息",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
      ),
      body: Column(
        children: [
          Flexible(
            child: Container(
              padding: EdgeInsets.all(12),
              margin: EdgeInsets.all(12),
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(5)),
              child: ListView(
                children: [
                  GestureDetector(
                    child: Row(
                      children: [
                        Text(
                          "头像",
                          style: TextStyle(
                              color: CommonColor.color33,
                              fontSize: 15,
                              fontWeight: FontWeight.w600),
                        ),
                        Spacer(),
                        imgFeed != null
                            ? CircleAvatar(
                                child: Image.file(
                                  File(imgFeed?.path ?? ''),
                                  width: 68,
                                  height: 68,
                                  fit: BoxFit.cover,
                                  alignment: Alignment.topCenter,
                                ),
                              )
                            : uerInfo?.profile?.isNotEmpty == true
                                ? CachedNetworkImage(
                                    imageBuilder: (context, image) =>
                                        CircleAvatar(
                                          backgroundImage: image,
                                        ),
                                    errorWidget: (context, url, error) =>
                                        CircleAvatar(
                                          backgroundImage: AssetImage(
                                              UserFeedBackImgs.user_male),
                                        ),
                                    width: 68,
                                    height: 68,
                                    imageUrl: UserFeedBackImgs.url +
                                        (uerInfo?.profile ?? ''))
                                : Image.asset(
                                    UserFeedBackImgs.user_male,
                                    height: 60,
                                  )
                      ],
                    ),
                    onTap: () {
                      getLostData();
                    },
                  ),
                  Divider(
                    height: 35,
                    thickness: 0.5,
                    color: CommonColor.colorEE,
                  ),
                  GestureDetector(
                    onTap: () {
                      QmToast.toast('暂不支持修改');
                      // _showNameDialog(_nameController, (value) {
                      //   if (value == 1) {
                      //     setState(() {});
                      //   }
                      // });
                    },
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          "姓名",
                          style: TextStyle(
                              color: CommonColor.color33,
                              fontSize: 15,
                              fontWeight: FontWeight.w600),
                        ),
                        Spacer(),
                        Text(
                          uerInfo?.username ?? "姓名",
                          style: TextStyle(
                              color: CommonColor.color33, fontSize: 15),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Icon(
                          Icons.arrow_forward_ios,
                          size: 15,
                        )
                      ],
                    ),
                  ),
                  Divider(
                    height: 35,
                    thickness: 0.5,
                    color: CommonColor.colorEE,
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        "性别",
                        style: TextStyle(
                            color: CommonColor.color33,
                            fontSize: 15,
                            fontWeight: FontWeight.w600),
                      ),
                      Spacer(),
                      Text(
                        '男',
                        style:
                            TextStyle(color: CommonColor.color33, fontSize: 15),
                      ),
                      SizedBox(
                        width: 40,
                        child: Checkbox(
                          value: curSex == 1,
                          activeColor: CommonColor.colorMainGreen, //选中时的颜色
                          onChanged: (value) {
                            setState(() {
                              if (value == true) curSex = 1;
                            });
                          },
                        ),
                      ),
                      Text(
                        '女',
                        style:
                            TextStyle(color: CommonColor.color33, fontSize: 15),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      SizedBox(
                        width: 10,
                        child: Checkbox(
                          value: curSex == 2,
                          activeColor: CommonColor.colorMainGreen, //选中时的颜色
                          onChanged: (value) {
                            setState(() {
                              if (value == true) curSex = 2;
                            });
                          },
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                    ],
                  ),
                  Divider(
                    height: 35,
                    thickness: 0.5,
                    color: CommonColor.colorEE,
                  ),
                  GestureDetector(
                    onTap: () {
                      _showMemberDialog("修改联系方式", '取消', '确定', _phoneController,
                          (value) {
                        if (value == 1) {
                          setState(() {});
                        }
                      });
                    },
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          "联系方式",
                          style: TextStyle(
                              color: CommonColor.color33,
                              fontSize: 15,
                              fontWeight: FontWeight.w600),
                        ),
                        Spacer(),
                        Text(
                          uerInfo?.mobile ?? "暂无",
                          style: TextStyle(
                              color: CommonColor.color33, fontSize: 15),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Icon(
                          Icons.arrow_forward_ios,
                          size: 15,
                        )
                      ],
                    ),
                  ),
                  Divider(
                    height: 35,
                    thickness: 0.5,
                    color: CommonColor.colorEE,
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        "个人简介",
                        style: TextStyle(
                            color: CommonColor.color33,
                            fontSize: 15,
                            fontWeight: FontWeight.w600),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  TextField(
                    maxLines: 6,
                    maxLength: 140,
                    controller: _controllerDes,
                    decoration: const InputDecoration(
                      counterText: '',
                      contentPadding: EdgeInsets.fromLTRB(10, 0, 10, 15),
                      fillColor: Color(0x2083DF00),
                      filled: true,
                      enabledBorder: OutlineInputBorder(
                        /*边角*/
                        borderRadius: BorderRadius.all(
                          Radius.circular(5), //边角为5
                        ),
                        borderSide: BorderSide(
                          color: Colors.white, //边线颜色为白色
                          width: 1, //边线宽度为2
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.white, //边框颜色为白色
                          width: 1, //宽度为5
                        ),
                        borderRadius: BorderRadius.all(
                          Radius.circular(5), //边角为30
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              _update();
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(left: 40, right: 40, bottom: 40),
              height: 45,
              decoration: BoxDecoration(
                  color: Color(0xff83DF00),
                  borderRadius: BorderRadius.circular(4)),
              child: const Text(
                "保  存",
                style: TextStyle(
                    color: Color(0XFF333333),
                    fontSize: 16,
                    fontWeight: FontWeight.w500),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _getUser();
  }

  Future<String> _uploadImg(XFile locFile) async {
    var file = File(locFile.path);
    BaseDataEntity model = await CommonClient().commonUpFile(file);
    if (model.status == true) {
      return model.data ?? '';
    } else {
      return '';
    }
  }

  _update() async {
    try {
      var profile = uerInfo?.profile;
      if (imgFeed != null) {
        profile = await _uploadImg(imgFeed!);
      }
      var extraD = UsrExtraEntity();
      extraD.des = _controllerDes.text;
      var res = await CommonClient().updateUser(
          uerInfo?.id ?? '',
          uerInfo?.email ?? '',
          uerInfo?.password ?? '',
          _nameController.text,
          _phoneController.text,
          profile ?? "",
          curSex,
          1,
          extra: jsonEncode(extraD));
      if (res.status == true)
        Get.back(result: true);
      else
        QmToast.toast(res.message ?? '错误');
    } catch (e) {
      print(e);
    }
  }

  _getUser() async {
    try {
      var res = await CommonClient().getUser(SpUtil.getString("uid") ?? '');
      print(jsonEncode(res.data ?? ""));
      List<dynamic> data = jsonDecode(res.data ?? "");
      if (data != null) {
        uerInfo = UerInfoEntity.fromJson(data[0]);
        setState(() {
          curSex = uerInfo?.sex ?? 1;
          _nameController.text = uerInfo?.username ?? '';
          _phoneController.text = uerInfo?.mobile ?? '';
          _controllerDes.text =
              UsrExtraEntity.fromJson(jsonDecode(uerInfo?.extra ?? "")).des ??
                  '';
        });
      }
    } catch (e) {
      print(e);
    }
  }

  _showNameDialog(
    TextEditingController controller,
    ValueChanged<int>? action,
  ) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return WillPopScope(
              onWillPop: () async => false,
              child: Scaffold(
                  backgroundColor: Colors.transparent,
                  body: Center(
                    child: SingleChildScrollView(
                      child: Container(
                        margin: EdgeInsets.only(left: 48, right: 48),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(
                              height: 29,
                            ),
                            Text(
                              "修改姓名",
                              style: TextStyle(
                                  fontSize: 18,
                                  color: CommonColor.color33,
                                  fontWeight: FontWeight.w700),
                            ),
                            SizedBox(
                              height: 25,
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 15, right: 15),
                              padding: EdgeInsets.only(left: 15, right: 15),
                              decoration: BoxDecoration(
                                  color: CommonColor.colorF8,
                                  borderRadius: BorderRadius.circular(4)),
                              child: TextField(
                                maxLines: 1,
                                maxLength: 5,
                                textAlign: TextAlign.start,
                                controller: controller,
                                enableInteractiveSelection: true,
                                style: TextStyle(
                                  color: CommonColor.color33,
                                  fontSize: 15,
                                  textBaseline: TextBaseline.alphabetic,
                                ),
                                cursorColor: CommonColor.color66,
                                decoration: InputDecoration(
                                  counterText: '',
                                  border: InputBorder.none,
                                  hintStyle: TextStyle(
                                      fontSize: 15, color: CommonColor.colorF5),
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 25,
                            ),
                            Divider(
                              height: 1,
                              color: CommonColor.colorEE,
                            ),
                            Container(
                              height: 50,
                              child: Flex(
                                direction: Axis.horizontal,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: GestureDetector(
                                      onTap: () {
                                        Navigator.pop(context);
                                        action!(0);
                                      },
                                      child: Text(
                                        '取消',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontSize: 18,
                                            color: CommonColor.color99),
                                      ),
                                    ),
                                  ),
                                  VerticalDivider(
                                    width: 1,
                                    color: CommonColor.colorEE,
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: GestureDetector(
                                      onTap: () {
                                        if (controller.text.isNotEmpty) {
                                          uerInfo?.username = controller.text;
                                          Navigator.pop(context);
                                          action!(1);
                                        } else
                                          QmToast.toast("请输入姓名");
                                      },
                                      child: Text(
                                        '确定',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontSize: 18,
                                            color: CommonColor.colorMainGreen),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )));
        });
  }

  _showMemberDialog(
    String title,
    String cancel,
    String sure,
    TextEditingController controller,
    ValueChanged<int>? action,
  ) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return WillPopScope(
              onWillPop: () async => false,
              child: Scaffold(
                  backgroundColor: Colors.transparent,
                  body: Center(
                    child: SingleChildScrollView(
                      child: Container(
                        margin: EdgeInsets.only(left: 48, right: 48),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(
                              height: 29,
                            ),
                            Text(
                              title,
                              style: TextStyle(
                                  fontSize: 18,
                                  color: CommonColor.color33,
                                  fontWeight: FontWeight.w700),
                            ),
                            SizedBox(
                              height: 25,
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 15, right: 15),
                              padding: EdgeInsets.only(left: 15, right: 15),
                              decoration: BoxDecoration(
                                  color: CommonColor.colorF8,
                                  borderRadius: BorderRadius.circular(4)),
                              child: TextField(
                                maxLines: 1,
                                textAlign: TextAlign.start,
                                inputFormatters: [
                                  //限制只允许输入数字
                                  FilteringTextInputFormatter.digitsOnly,
                                  // //限制输入长度不超过11位
                                  LengthLimitingTextInputFormatter(11),
                                ],
                                controller: controller,
                                keyboardType: TextInputType.number,
                                enableInteractiveSelection: true,
                                style: TextStyle(
                                  color: CommonColor.color33,
                                  fontSize: 15,
                                  textBaseline: TextBaseline.alphabetic,
                                ),
                                cursorColor: CommonColor.color66,
                                decoration: InputDecoration(
                                  counterText: '',
                                  border: InputBorder.none,
                                  hintStyle: TextStyle(
                                      fontSize: 15, color: CommonColor.colorF5),
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 25,
                            ),
                            Divider(
                              height: 1,
                              color: CommonColor.colorEE,
                            ),
                            Container(
                              height: 50,
                              child: Flex(
                                direction: Axis.horizontal,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: GestureDetector(
                                      onTap: () {
                                        Navigator.pop(context);
                                        action!(0);
                                      },
                                      child: Text(
                                        cancel,
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontSize: 18,
                                            color: CommonColor.color99),
                                      ),
                                    ),
                                  ),
                                  VerticalDivider(
                                    width: 1,
                                    color: CommonColor.colorEE,
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: GestureDetector(
                                      onTap: () {
                                        if (controller.text.isNotEmpty &&
                                            controller.text.length >= 11) {
                                          uerInfo?.mobile = controller.text;
                                          Navigator.pop(context);
                                          action!(1);
                                        } else
                                          QmToast.toast("请输入正确格式的手机号");
                                      },
                                      child: Text(
                                        sure,
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontSize: 18,
                                            color: CommonColor.colorMainGreen),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )));
        });
  }
}
